package com.zyx.flinkdemo.sql.func;

import com.zyx.flinkdemo.pojo.WaterSensor;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.annotation.DataTypeHint;
import org.apache.flink.table.annotation.FunctionHint;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @author zyx
 * @since 2021/5/30 16:59
 * desc: UDAF(表值函数)案例
 */
public class UdafDemo {
    public static void main(String[] args) throws Exception {
        // 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 2.读取端口数据创建流并转换每一行数据为JavaBean对象
        SingleOutputStreamOperator<WaterSensor> waterSensorDs = env
                .socketTextStream("linux201", 7777)
                .map(line -> {
                    String[] split = line.split(",");
                    return new WaterSensor(split[0],
                            Long.parseLong(split[1]),
                            Integer.parseInt(split[2]));
                });

        // 3.将流转换为表
        Table table = tableEnv.fromDataStream(waterSensorDs);
        tableEnv.createTemporaryView("water_sensor", table);

        // 4.注册udf
        tableEnv.createTemporarySystemFunction("mysplit", SplitFunction.class);

        // 5.使用udf
        // 使用TableAPI查询udf
        /*tableEnv
                .from("water_sensor")
                .joinLateral(call("mysplit", $("id")))
                .select($("id"), $("word"), $("length"))
                .execute()
                .print();*/
        // 使用SQL查询udf
        tableEnv
                // 写法1: 添加侧写表
                //.sqlQuery("select id, word, length from water_sensor, LATERAL TABLE(mysplit(id))")
                // 写法2: 左外连接侧写表
                /*.sqlQuery("select id, word, length from water_sensor left join " +
                        "LATERAL TABLE(mysplit(id)) on true")*/
                // 写法3: 左外连接侧写表 + 侧写表字段取别名
                .sqlQuery("select id, newWord, newLength from water_sensor left join " +
                        "LATERAL TABLE(mysplit(id)) AS T(newWord, newLength) on true")
                .execute()
                .print();

        // 6.执行任务
        env.execute();
    }

    @FunctionHint(output = @DataTypeHint("ROW<word STRING, length INT>"))
    public static class SplitFunction extends TableFunction<Row> {
        public void eval(String str) {
            for (String s : str.split("_")) {
                // use collect(...) to emit a row
                collect(Row.of(s, s.length()));
            }
        }
    }
}
